<template>
  <div class="cropper-wrap">
    <div style="position:relative;width:100%;height:400px;">
      <img ref="image" :src="imageSrc" alt="Crop me" style="max-width:100%;max-height:100%;">
    </div>
    <div style="margin-top:10px;">
      <label for="aspectRatio">选择宽高比:</label>
      <select id="aspectRatio" v-model="selectedAspectRatio">
        <option value="NaN">自由比例</option>
        <option value="16 / 9">16:9</option>
        <option value="4 / 3">4:3</option>
        <option value="1 / 1">1:1</option>
      </select>

      <button @click="zoomIn">放大</button>
      <button @click="zoomOut">缩小</button>
      <button @click="resetZoom">重置</button>
      <button @click="cropImage">确认裁剪</button>
    </div>
  </div>
</template>

<script>
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';

export default {
  props: {
    imageSrc: String,
  },
  data() {
    return {
      cropper: null,
      croppedImageUrl: '',
      selectedAspectRatio: 'NaN', // 默认设置为自由比例
      zoomLevel: 0, // 初始缩放级别
    };
  },
  watch: {
    imageSrc(newVal) {
      this.updateCropper();
    },
    selectedAspectRatio(newValue) {
      if (this.cropper) {
        this.cropper.setAspectRatio(eval(newValue));
      }
    }
  },
  methods: {
    updateCropper() {
      if (this.cropper) {
        this.cropper.destroy(); // 销毁旧的裁剪器实例
      }

      this.$nextTick(() => { // 确保DOM已更新
        const image = this.$refs.image;
        this.cropper = new Cropper(image, {
          aspectRatio: eval(this.selectedAspectRatio),
          viewMode: 1,
          cropBoxResizable: true,
          ready: () => {
            // 可选：初始化时设置默认裁剪框大小
            const canvasData = this.cropper.getCanvasData();
            const cropBoxData = this.cropper.getCropBoxData();
            this.cropper.setCropBoxData({
              left: canvasData.left + (canvasData.width - cropBoxData.width) / 2,
              top: canvasData.top + (canvasData.height - cropBoxData.height) / 2,
              width: 300, // 设置默认宽度
              height: 200, // 设置默认高度
            });
          }
        });
      });
    },
    cropImage() {
      const canvas = this.cropper.getCroppedCanvas();
      this.croppedImageUrl = canvas.toDataURL();
      this.$emit('cropped', this.croppedImageUrl);
    },
    zoomIn() {
      this.zoomLevel += 0.1;
      this.cropper.zoom(this.zoomLevel);
    },
    zoomOut() {
      this.zoomLevel -= 0.1;
      this.cropper.zoom(this.zoomLevel);
    },
    resetZoom() {
      this.zoomLevel = 0;
      this.cropper.reset();
    }
  },
  mounted() {
    this.updateCropper(); // 初始化裁剪器
  },
  beforeDestroy() {
    if (this.cropper) {
      this.cropper.destroy();
    }
  }
};
</script>

<style scoped>
.cropper-wrap {
  text-align: center;
}
</style>
